<?php

namespace App\Console\Commands\Fix;

use App\Console\BaseCommand;
use App\Consts\GlobalConst;
use App\Models\UserAttention;
use Illuminate\Database\Query\Builder;

/**
 * 广场数据修复脚本
 * Class FakeFixCommand
 * @package App\Console\Commands\Fix
 */
class SquareFixCommand extends BaseCommand
{

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'fix:square {action}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'fix square data';

    /**
     * 广场数据修复 - 删除重复动态
     * @return int
     */
    public function attention()
    {
        $subMode = $this->_getSubModel();
        $finish = $subMode->count();
        // 每 1000 单位合并处理一次
        $subMode->chunk(1000, function ($list) use ($finish) {
            foreach ($list as $item) {
                static $index = 1;
                $delCount = 0;
                // 查询数据列表
                $repeat = UserAttention::getInstance($item->user_attention_id)
                    ->where('user_attention_id', $item->user_attention_id)
                    ->where('target_id', $item->target_id)
                    ->where('user_id', $item->user_id)
                    ->where('is_deleted', GlobalConst::IS_NOT_DELETE)
                    ->orderByDesc('id')
                    ->get();
                // 删除多余数据
                if ($repeat->count() >= 2) {
                    foreach ($repeat as $key => $attention) {
                        if (!$key) continue;
                        $attention->update(['is_deleted' => GlobalConst::IS_DELETED]);
                        $delCount++;
                    }
                }
                $tbName = UserAttention::getTableNameById($item->user_attention_id);
                if (!empty($delCount)) {
                    $info = "[$index/$finish] delete data from `{$tbName}` - " . json_encode($item);
                } else {
                    $info = "[$index/$finish] check data `{$tbName}` - {$item->id} .";
                }
                // log info
                $this->info($info);
                if ($delCount) $this->logger($info, false, 'script');
                $index++;
            }
        });
        return 1;
    }

    /**
     * get sub model
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|mixed
     */
    private function _getSubModel()
    {
        $subMode = UserAttention::getSubModel(function (Builder $query) {
            $query->where('is_deleted', GlobalConst::IS_NOT_DELETE);
        }, ['id', 'user_attention_id', 'target_id', 'user_id'])->orderByDesc('user_attention_id');
        return $subMode;
    }

}
